package com.mobilezu.mobile.common.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import net.sf.json.JSONObject;
import org.apache.struts2.ServletActionContext;
import com.mobilezu.mobile.common.model.SystemUser;
import com.mobilezu.mobile.common.service.SystemUserServiceable;
import com.mobilezu.mobile.pushserver.model.PushUser;
import com.mobilezu.mobile.pushserver.service.PushUserService;
import com.opensymphony.xwork2.ActionSupport;
/**
 * 系统服务
 * @author Leo
 *
 */
public class SystemAction extends ActionSupport {
	private SystemUserServiceable systemUserService;
	private PushUserService pushUserService;
	
	
	public void setSystemUserService(SystemUserServiceable systemUserService) {
		this.systemUserService = systemUserService;
	}
	
	
	public void setPushUserService(PushUserService pushUserService) {
		this.pushUserService = pushUserService;
	}


	private static final long serialVersionUID = -2044445606370719197L;

	/**
	 * 系统登录方法
	 * @return 返回消息
	 * @throws IOException 
	 * @throws ServletException 
	 */
	public String doLogin() throws ServletException, IOException {
		String result = "";
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpSession session=request.getSession();
		String userName = request.getParameter("txtUserName");
		String userPwd = request.getParameter("txtUserPassWord");
		SystemUser user=systemUserService.getSystemUserByUsername(userName);
		if(user!=null){
			//执行认证操作
			if(userPwd!=null&&userPwd.trim().equals(user.getPassword())){
				result = "SUCCESS";
			}else{
				result = "ERROR";
				session.setAttribute("message","认证失败，密码错误！");
			}
			
		}else{
			//提示用户不存在
			result = "ERROR";
			session.setAttribute("message", "认证失败，用户不存在！");
		}
		return result;
	}
	
	/**
	 * 获取所有用户方法
	 * @return 返回操作码
	 */
	public String doGetAllUser() throws ServletException, IOException{
		//执行获取所有用户
		HttpServletRequest request=ServletActionContext.getRequest();
		HttpServletResponse response=ServletActionContext.getResponse();
		
		response.setContentType("text/html");
		request.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		String returnStr = "{}";
		try {
			List<PushUser> userList = pushUserService.getPushUsers();

			if (userList != null&& userList.size() > 0) {
				List<JSONObject> userListArray=new ArrayList<JSONObject>();
				for (PushUser user : userList) {
					userListArray.add(user.toJSONObject());
				}
				returnStr =userListArray.toString();
			} else {
				returnStr = "{}";
			}
		} catch (Exception e) {
			returnStr = "{}";
		} finally {
			out.print(returnStr);
			out.flush();
			out.close();
		}
		return null;
	}

	
}
